package com.shjn.squirrel.utils;

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * okhttp网络请求工具类
 */
public class OkhttpHelper {

    //初始化OkHttpClient
    private static OkHttpClient mOkHttpClient = new OkHttpClient().newBuilder()
            .connectTimeout(30, TimeUnit.SECONDS).writeTimeout(30, TimeUnit.SECONDS)
            .readTimeout(30, TimeUnit.SECONDS).build();

    //重新请求，时间间隔,单位秒
    private static final int INTERVAL = 1;

    private OkhttpHelper() {
    }

    /**
     * GET异步请求
     *
     * @param requestUrl
     * @param responseCallback
     */
    public static void getRequest(String requestUrl, Callback responseCallback) {
        //构造Request对象
        Request request = new Request.Builder().get().url(requestUrl).build();
        //构造Call对象
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(responseCallback);
    }

    /**
     * POST异步请求
     *
     * @param requestUrl
     * @param mJsonStr
     */
    public static void postRequest(String requestUrl, String mJsonStr, Callback responseCallback) {
        //构造Json的请求对象
        RequestBody mRequestBody = RequestBody.create(MediaType.parse("application/json;chaset=utf-8"), mJsonStr);
        //构造Request对象
        Request request = new Request.Builder().post(mRequestBody).url(requestUrl).build();
        //构造Call对象
        Call mCall = mOkHttpClient.newCall(request);
        mCall.enqueue(responseCallback);
    }

    /**
     * 网络故障重连
     *
     * @param call
     * @param responseCallback
     */
    public static void requestAgain(Call call, Callback responseCallback) {
        try {
            Thread.sleep(INTERVAL * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //重新发起请求
        mOkHttpClient.newCall(call.request()).enqueue(responseCallback);
    }
}
